package ar.com.cema.methodology.analyzer.ui.servlet.json;

import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ar.com.cema.methodology.analyzer.model.Variable;
import ar.com.cema.methodology.analyzer.services.MethodologyUsageService;
import ar.com.cema.methodology.analyzer.services.beans.MethodologyUsageReport;
import ar.com.cema.methodology.analyzer.services.beans.ProjectConfiguration;
import ar.com.cema.methodology.analyzer.ui.ServiceLocator;
import ar.com.cema.methodology.analyzer.ui.UserInputDTO;

@WebServlet(name="MethodologyUsageJsonServlet", urlPatterns = { ServiceLocator.JSON_USAGE_REPORT_MP })
public class MethodologyUsageJsonServlet extends JsonProviderServlet {
	private static final long serialVersionUID = 1L;

	@Autowired
	private MethodologyUsageService methodologyUsageService;
	
	private Log logger = LogFactory.getLog(MethodologyUsageJsonServlet.class);

	public void setMethodologyUsageService(MethodologyUsageService methodologyUsageService) {
		this.methodologyUsageService = methodologyUsageService;
	}
	
	@Override
	protected String getJSON(HttpServletRequest request) {
		String json = request.getParameter("json");
		String[] jsonObjectArray = json.replace("[","").replace("]","").replace("},{", "};{").split(";");
		ProjectConfiguration projectConfiguration = new ProjectConfiguration();
		
		
		for (String string : jsonObjectArray) {
			UserInputDTO userInput = gson.fromJson(string, UserInputDTO.class);
			projectConfiguration.addVariable(new Variable(userInput.getVariableId().longValue()), userInput.getInput());
		}
		
		if ( logger.isDebugEnabled() ) {
			logger.debug("\n\n#########################################################################################################");
			logger.debug("JSON PARAMETER = " + json);
			Map<Variable, Integer> userConfiguration = projectConfiguration.getUserConfiguration();
			for (Variable variable : userConfiguration.keySet()) {
				logger.debug("Variable[id=" + variable.getId() + "] has user input=" + userConfiguration.get(variable));
			}
			logger.debug("#########################################################################################################\n\n");
		}

		MethodologyUsageReport report = methodologyUsageService.generateReportFor(projectConfiguration);
		return gson.toJson(report);
	}
}